<template>
    <div class="admin-ticket-processing">
      <h2>处理用户提交的售后工单</h2>
      <el-table :data="tickets" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="工单号" width="100"></el-table-column>
        <el-table-column prop="username" label="用户" width="100"></el-table-column>
        <el-table-column prop="ticketType" label="类型" width="100"></el-table-column>
        <el-table-column prop="description" label="描述"></el-table-column>
        <el-table-column prop="submitDate" label="提交日期" width="120"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ mapTicketStatus(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="openDialog(row)">处理</el-button>
            <el-button link type="info" size="small" @click="viewProgress(row)">进度</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-if="tickets.length === 0 && !loading" description="暂无工单"></el-empty>
  
      <el-dialog
        v-model="dialogVisible"
        title="处理工单"
        width="40%"
      >
        <el-form :model="currentTicket" label-width="100px">
          <el-form-item label="工单号">
            <el-input v-model="currentTicket.id" disabled></el-input>
          </el-form-item>
          <el-form-item label="用户">
            <el-input v-model="currentTicket.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="类型">
            <el-input v-model="currentTicket.ticketType" disabled></el-input>
          </el-form-item>
          <el-form-item label="描述">
            <el-input type="textarea" v-model="currentTicket.description" :rows="3" disabled></el-input>
          </el-form-item>
          <el-form-item label="当前状态">
            <el-input :value="mapTicketStatus(currentTicket.status)" disabled></el-input>
          </el-form-item>
          <el-form-item label="更新状态">
            <el-select v-model="newStatus" placeholder="请选择新状态">
              <el-option label="待处理" value="PENDING"></el-option>
              <el-option label="处理中" value="PROCESSING"></el-option>
              <el-option label="已完成" value="COMPLETED"></el-option>
              <el-option label="已关闭" value="CLOSED"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="新增进度">
            <el-input v-model="newProgressStep" placeholder="可选：添加新的进度步骤"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleUpdateTicket">保存</el-button>
          </span>
        </template>
      </el-dialog>
  
      <el-dialog
        v-model="progressDialogVisible"
        title="工单处理进度"
        width="30%"
      >
        <el-timeline v-if="selectedTicketProgress && selectedTicketProgress.length > 0">
          <el-timeline-item
            v-for="(activity, index) in selectedTicketProgress"
            :key="index"
            :timestamp="activity.timestamp || ''"
            placement="hollow"
          >
            {{ activity.step }}
          </el-timeline-item>
        </el-timeline>
        <p v-else>暂无进度信息。</p>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import { fetchAllServiceTickets, updateServiceTicketStatus } from '../../api'
  import { ElMessage } from 'element-plus'
  
  const tickets = ref([])
  const dialogVisible = ref(false)
  const currentTicket = ref({})
  const newStatus = ref('')
  const newProgressStep = ref('')
  
  const progressDialogVisible = ref(false)
  const selectedTicketProgress = ref([])
  const loading = ref(false)
  
  const loadTickets = async () => {
    loading.value = true
    try {
      const response = await fetchAllServiceTickets()
      if (response.data.success) {
        tickets.value = response.data.data
      } else {
        ElMessage.error(response.data.message || '获取工单失败！')
      }
    } catch (error) {
      ElMessage.error('加载工单出错！')
      console.error('Failed to fetch all tickets:', error)
    } finally {
      loading.value = false
    }
  }
  
  const getStatusTagType = (status) => {
    switch (status) {
      case 'PENDING': return 'warning'
      case 'PROCESSING': return ''
      case 'COMPLETED': return 'success'
      case 'CLOSED': return 'info'
      default: return 'info'
    }
  }
  
  const mapTicketStatus = (status) => {
    const statusMap = {
      'PENDING': '待处理',
      'PROCESSING': '处理中',
      'COMPLETED': '已完成',
      'CLOSED': '已关闭'
    }
    return statusMap[status] || status
  }
  
  const openDialog = (ticket) => {
    currentTicket.value = { ...ticket }
    newStatus.value = ticket.status
    newProgressStep.value = ''
    dialogVisible.value = true
  }
  
  const handleUpdateTicket = async () => {
    try {
      const response = await updateServiceTicketStatus(currentTicket.value.id, newStatus.value, newProgressStep.value)
      if (response.data.success) {
        ElMessage.success(response.data.message)
        dialogVisible.value = false
        await loadTickets()
      } else {
        ElMessage.error(response.data.message || '更新失败！')
      }
    } catch (error) {
      ElMessage.error('请求出错！')
      console.error('Failed to update ticket status:', error)
    }
  }
  
  const viewProgress = (ticket) => {
    const progressString = ticket.progress
    let progressArray = []
    try {
      if (progressString) {
        progressArray = JSON.parse(progressString)
      }
    } catch (e) {
      console.error("Failed to parse progress JSON:", e)
      progressArray = [progressString]
    }
  
    selectedTicketProgress.value = progressArray.map(step => ({ step, timestamp: new Date().toLocaleString() }))
    progressDialogVisible.value = true
  }
  
  onMounted(loadTickets)
  </script>
  
  <style scoped>
  .admin-ticket-processing {
    padding: 20px;
  }
  </style>